package com.sh;

import java.util.HashMap;
import java.util.Map;

public class MySimpleIoC {

    // 最简单的一级缓存：存放创建完成的 Bean
    private Map<String, Object> singletonObjects = new HashMap<>();

    public Object getBean(String beanName) {
        // 看看是否已经创建
        if (singletonObjects.containsKey(beanName)) {
            return singletonObjects.get(beanName);
        }

        // 创建 Bean
        Object bean = createBean(beanName);
        singletonObjects.put(beanName, bean);
        return bean;
    }

    // 创建 Bean 并注入依赖（手动控制）
    private Object createBean(String beanName) {
        if ("a".equals(beanName)) {
            return new A(); // 无依赖
        } else if ("b".equals(beanName)) {
            B b = new B();
            // 注入 A
            A a = (A) getBean("a");
            b.setA(a);
            return b;
        }

        throw new RuntimeException("未知的 bean: " + beanName);
    }
}
